package com.yj.ccs.abs.web.asset.mapper;

import com.yj.ccs.abs.web.asset.entity.Receipt;
import com.yj.ccs.abs.web.asset.entity.ReceiptListItem;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.List;

/**
 * Copyright 2018 (C) Yunjian-VC
 * Created on : 2018/3/22
 * Author     : Unbelievable9
 **/
@Repository
@Mapper
public interface ReceiptMapper {

    @Options(useGeneratedKeys = true, keyProperty = "item.id")
    @Insert("INSERT INTO `receipt` (asset_id, date, number, amount, money, create_time) " +
            "VALUES (#{item.asset_id}, #{item.date}, #{item.number}, #{item.amount}, #{item.money}, NOW())")
    void create(@Param("item") Receipt item);

    @Update("UPDATE `receipt` SET date = #{item.date}, number = #{item.number}, amount = #{item.amount}, money = #{item.money} " +
            "WHERE id = #{item.id}")
    void update(@Param("item") Receipt item);

    @Delete("DELETE FROM `receipt` WHERE id = #{id}")
    void deleteById(@Param("id") Long id);

    @Select("SELECT * FROM `receipt` WHERE id = #{id} LIMIT 1")
    Receipt getById(@Param("id") Long id);

    @Select("SELECT r.id, r.date, r.number, r.amount, r.money, a.url, a.`name`, a.type FROM `receipt` r " +
            "LEFT JOIN `attachment` a ON (r.id = a.reference_id) " +
            "WHERE a.category = 15 AND r.asset_id = #{asset_id} " +
            "GROUP BY r.id")
    List<ReceiptListItem> getListItemByAssetId(@Param("asset_id") Long asset_id);

    @Select("SELECT SUM(amount) FROM receipt WHERE asset_id = #{asset_id}")
    BigDecimal getTotalAmountByAssetId(@Param("asset_id") Long asset_id);

    @Select("SELECT SUM(money) FROM receipt WHERE asset_id = #{asset_id}")
    BigDecimal getTotalMoneyByAssetId(@Param("asset_id") Long asset_id);
}
